<?php

Class ManagersController extends AppController {
	var $layout = "manager";
	var $helpers = array("Html","Manager","Ajax","Javascript");
	var $components = array('Session','RequestHandler');
	var $name = "Managers";
	var $persistModel = true;


	function menu(){
		if ($this->Auth->user('user_type') == 1)
		{
			$menu = "<ul id='main_menu' class='main_menu'>
				 <li class='limenu' ><a href='#' ><span class='ico gray home'></span><b>Quản lý kho sỉ</b></a>";
			$menu .= "<ul><li><a href='/SaleManagement/managers/warehouse_invoice' >Nhập kho</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/wholesale_invoice' >Bán hàng</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/transfer_invoice' >Chuyển hàng</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/wholesale_wh_status' >Hiện trạng kho</a></li></ul></li>";
			$menu .= "<li class='limenu' ><a href='#' ><span class='ico gray cabinet'></span><b>Quản lý kho lẻ</b></a>";
			$menu .= "<ul><li><a href='/SaleManagement/managers/retail_invoice' >Bán hàng</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/retail_wh_status' >Hiện trạng kho</a></li></ul></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/delivery_managerment' ><span class='ico gray shadow spreadsheet'></span><b>Quản lý giao hàng</b></a></li>";
			$menu .= "<li class='limenu' ><a href='#' ><span class='ico gray shadow window'></span><b>Quản lý hóa đơn</b></a>";
			$menu .= "<ul><li><a href='/SaleManagement/managers/warehouse' >Hóa đơn nhập kho</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/transfer' >Hóa đơn chuyển kho</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/wholesale' >Hóa đơn bán sỉ</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/retail' >Hóa đơn bán lẻ</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/delivery' >Hóa đơn giao hàng</a></li></ul></li>";
			$menu .= "<li class='limenu' ><a href='#' ><span class='ico gray shopping_basket'></span><b>Quản lý sản phẩm</b></a>";
			$menu .= "<ul><li><a href='/SaleManagement/managers/product' >Sản phẩm</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/product_type' >Loại sản phẩm</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/unit' >Đơn vị sản phẩm</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/promotion' >Khuyến mãi</a></li></ul></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/vendor' ><span class='ico gray briefcase'></span><b>Quản lý đối tác</b></a></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/customer' ><span class='ico gray user'></span><b>Quản lý khách hàng</b></a></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/employee' ><span class='ico gray group'></span><b>Quản lý nhân viên</b></a></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/statistic' ><span class='ico gray stats_bars'></span><b>Thống kê</b></a></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/other' ><span class='ico gray add'></span><b>Thao tác khác</b></a></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/personal_information' ><span class='ico gray id'></span><b>Thông tin cá nhân</b></a></li>";
			return $menu;
		}
		else {
			$menu = "<ul id='main_menu' class='main_menu'>
				 <li class='limenu' ><a href='#' ><span class='ico gray home'></span><b>Quản lý kho sỉ</b></a>";
			$menu .= "<ul><li><a href='/SaleManagement/managers/warehouse_invoice' >Nhập kho</a></li>";
			$menu .= "<li><a href='/SaleManagement/managers/wholesale_invoice' >Bán hàng</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/transfer_invoice' >Chuyển hàng</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/wholesale_wh_status' >Hiện trạng kho</a></li>";
			$menu .= "</ul></li>";
			$menu .= "<li class='limenu' ><a href='#' ><span class='ico gray cabinet'></span><b>Quản lý kho lẻ</b></a>";
			$menu .= "<ul><li><a href='/SaleManagement/managers/retail_invoice' >Bán hàng</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/retail_wh_status' >Hiện trạng kho</a></li>";
			$menu .= "</ul></li>";
			//$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/delivery_managerment' ><span class='ico gray shadow spreadsheet'></span><b>Quản lý giao hàng</b></a></li>";
			//$menu .= "<li class='limenu' ><a href='#' ><span class='ico gray shadow window'></span><b>Quản lý hóa đơn</b></a>";
			//$menu .= "<ul><li><a href='/SaleManagement/managers/warehouse' >Hóa đơn nhập kho</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/transfer' >Hóa đơn chuyển kho</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/wholesale' >Hóa đơn mua sỉ</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/retail' >Hóa đơn mua lẻ</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/delivery' >Hóa đơn giao hàng</a></li></ul></li>";
			//$menu .= "<li class='limenu' ><a href='#' ><span class='ico gray shopping_basket'></span><b>Quản lý sản phẩm</b></a>";
			//$menu .= "<ul><li><a href='/SaleManagement/managers/product' >Sản phẩm</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/product_type' >Loại sản phẩm</a></li>";
			//$menu .= "<li><a href='/SaleManagement/managers/unit' >Đơn vị sản phẩm</a></li></ul></li>";
			//$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/vendor' ><span class='ico gray briefcase'></span><b>Quản lý đối tác</b></a></li>";
			//$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/customer' ><span class='ico gray user'></span><b>Quản lý khách hàng</b></a></li>";
			//$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/employee' ><span class='ico gray group'></span><b>Quản lý nhân viên</b></a></li>";
			//$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/statistic' ><span class='ico gray stats_bars'></span><b>Thống kê</b></a></li>";
			$menu .= "<li class='limenu' ><a href='/SaleManagement/managers/personal_information' ><span class='ico gray id'></span><b>Thông tin cá nhân</b></a></li>";
			return $menu;
		}

	}

	function audit(){

		$this->set('title_for_layout','Manager Site');
		index();
	}

	function index(){
		$this->set('title_for_layout','Manager Site');
		$this->set('menu',$this->menu());
	}


	function warehouse_invoice(){
		//if ($this->Auth->user('level') != 1) {
		//	$this->Auth->allow("index");
		//	$this->redirect("error_authorization");
		//}
		$this->set('title_for_layout','Nhập kho - Manager Site');
		$this->set('vendors',$this->Manager->query('select v.id,v.name from vendors v'));
		$this->set('products',$this->Manager->query('select * from products p, units u where p.unit_id = u.id'));
		$this->set('types',$this->Manager->query('select * from product_types'));
		$this->set('units',$this->Manager->query('select * from units'));
		$this->set('menu',$this->menu());
			
	}
	function wholesale_invoice(){
		$this->set('title_for_layout','Bán hàng - Manager Site');
		$this->set('customers',$this->Manager->query('select c.id,c.name from customers c'));
		$this->set('products',$this->Manager->query('select * from products p, units u
														WHERE p.unit_id = u.id AND quantity_wholesale > 0 '));
		$this->set('types',$this->Manager->query('select * from product_types'));
		$this->set('units',$this->Manager->query('select * from units'));
		$this->set('menu',$this->menu());
	}
	function transfer_invoice(){
		$this->set('title_for_layout','Chuyển hàng - Manager Site');
		$this->set('list_product',$this->Manager->query('SELECT p.id,p.`name`,p.price_wholesale, p.quantity_wholesale
														FROM products p
														WHERE p.quantity_wholesale > 0
														ORDER BY id'));
		$this->set('menu',$this->menu());
	}
	function wholesale_wh_status(){
		$this->set('title_for_layout','Hiện trạng kho - Manager Site');
		$this->set('list_all_product',$this->Manager->query('SELECT p.`name`,p.id, p.price_wholesale, p.quantity_wholesale
														FROM products p 
														WHERE p.product_retail IS NOT NULL
														'));
		$this->set('list_product_out_of_stock',$this->Manager->query('SELECT p.`name`,p.id, p.price_wholesale, p.quantity_wholesale
														FROM products p
														WHERE p.quantity_wholesale = 0 AND p.product_retail IS NOT NULL
														'));
		$this->set('menu',$this->menu());
	}

	function error_authorization(){
		$this->set('title_for_layout','Lỗi truy cập');
		$this->set('menu',$this->menu());
	}


	function retail_invoice(){
		$this->set('title_for_layout','Xuất kho - Manager Site');
		$this->set('customers',$this->Manager->query('select c.id,c.name from customers c'));
		$this->set('products',$this->Manager->query('select * from products p, units u  where p.unit_id = u.id AND quantity_retail != 0'));
		$this->set('types',$this->Manager->query('select * from product_types'));
		$this->set('units',$this->Manager->query('select * from units'));
		$this->set('menu',$this->menu());
	}
	function retail_wh_status(){
		$this->set('title_for_layout','Hiện trạng kho - Manager Site');
		$this->set('list_all_product',$this->Manager->query('SELECT p.id,p.`name`,p.price_retail, p.quantity_retail
														FROM products p
														WHERE p.product_retail IS NULL'));
		$this->set('list_product_out_of_stock',$this->Manager->query('SELECT p.id,p.`name`,p.price_retail, p.quantity_retail
														FROM products p
														WHERE p.quantity_retail = 0 AND p.product_retail IS NULL'));
		$this->set('list_product_not_price',$this->Manager->query('SELECT p.id,p.`name`,p.price_retail, p.quantity_retail
														FROM products p
														WHERE p.price_retail = 0 AND p.product_retail IS NULL'));
		$this->set('menu',$this->menu());
	}
	function delivery_managerment(){
		$this->set('title_for_layout','Quản lý giao hàng - Manager Site');
		$this->set('list_wh_delivery',$this->Manager->query('SELECT wh.id,c.`name`, c.address, c.phone, wh.total, wh.date
														FROM wholesale_invoices wh,customers c
														WHERE wh.customer_id = c.id AND wh.status = 1'));
		$this->set('list_car',$this->Manager->query('SELECT c.id,c.number
														FROM cars c'));
		$this->set('list_driver',$this->Manager->query('SELECT e.id,e.name
														FROM employees e
														WHERE e.employee_type_id = 3 or id = 4 AND e.delete = 0'));
		$this->set('list_transfomer',$this->Manager->query('SELECT e.id,e.name
														FROM employees e
														WHERE e.employee_type_id = 4 AND e.delete = 0'));
		$this->set('menu',$this->menu());
	}
	function warehouse(){
		$this->set('title_for_layout','Hóa đơn nhập kho - Manager Site');
		$this->set('menu',$this->menu());
		$this->set('vendors',$this->Manager->query('select v.id,v.name from vendors v'));
		$SQL = "SELECT wh.id,v.`name`,wh.total,wh.time
			 FROM wh_invoices wh,vendors v
			 WHERE wh.vendor_id = v.id AND wh.delete = 0";
		$WHERE = "";
		$isSearch = 0;
		if(isset($_POST['idInvoice']) && $_POST['idInvoice'] != "")
		{
			$idInvoice = $_POST['idInvoice'];
			$WHERE = $WHERE." AND wh.id = ".$idInvoice;
		}
		if(isset($_POST['choose_vendor']) && $_POST['choose_vendor'] != "")
		{
			$choose_vendor = $_POST['choose_vendor'];
			$WHERE = $WHERE." AND wh.vendor_id = ".$choose_vendor;
		}
		if(isset($_POST['dateStart']) && $_POST['dateStart'] != "")
		{
			$dateStart = $_POST['dateStart'];
			$WHERE = $WHERE." AND wh.time >= '".$dateStart."'";
		}
		if(isset($_POST['dateEnd']) && $_POST['dateEnd'] != "")
		{
			$dateEnd = $_POST['dateEnd'];
			$WHERE = $WHERE." AND wh.time <= '".$dateEnd."'";
		}
		if(isset($_POST['totalStart']) && $_POST['totalStart'] != "")
		{
			$totalStart = $_POST['totalStart'];
			$WHERE = $WHERE." AND wh.total >= ".$totalStart;
		}
		if(isset($_POST['totalEnd']) && $_POST['totalEnd'] != "")
		{
			$totalEnd = $_POST['totalEnd'];
			$WHERE = $WHERE." AND wh.total <= ".$totalEnd;
		}
		if(isset($_POST['isSearch']))
		{
			$isSearch = $_POST['isSearch'];
		}
		$SQL = $SQL.$WHERE;
		$this->set('isSearch',$isSearch);
		$this->set('list_invoice',$this->Manager->query($SQL));
		if(isset($_GET['id']))
		{
			$id = $_GET['id'];
			$query = 'SELECT * FROM wh_invoices_wh_wholesales wh,products p WHERE wh.product_id = p.id AND wh.wh_invoice_id='.$id ;
			$result = $this->Manager->query($query);
			$this->set('list_product',$result);
		}
	}
	function transfer(){
		$this->set('title_for_layout','Hóa đơn chuyển kho - Manager Site');
		$this->set('products',$this->Manager->query('select * from products p, units u where p.unit_id = u.id'));
		$SQL = "SELECT p.`name`,tr.id,tr.quantity,tr.time
				FROM products p, transfer_invoices tr
				WHERE p.id = tr.product_id";
		$WHERE = "";
		$isSearch = 0;
		if(isset($_POST['idInvoice']) && $_POST['idInvoice'] != "")
		{
			$idInvoice = $_POST['idInvoice'];
			$WHERE = $WHERE." AND tr.id = ".$idInvoice;
		}
		if(isset($_POST['choose_product']) && $_POST['choose_product'] != "")
		{
			$choose_product = $_POST['choose_product'];
			$WHERE = $WHERE." AND tr.product_id = ".$choose_product;
		}
		if(isset($_POST['dateStart']) && $_POST['dateStart'] != "")
		{
			$dateStart = $_POST['dateStart'];
			$WHERE = $WHERE." AND tr.time >= '".$dateStart."'";
		}
		if(isset($_POST['dateEnd']) && $_POST['dateEnd'] != "")
		{
			$dateEnd = $_POST['dateEnd'];
			$WHERE = $WHERE." AND tr.time <= '".$dateEnd."'";
		}
		if(isset($_POST['quantityStart']) && $_POST['quantityStart'] != "")
		{
			$quantityStart = $_POST['quantityStart'];
			$WHERE = $WHERE." AND tr.quantity >= ".$quantityStart;
		}
		if(isset($_POST['quantityEnd']) && $_POST['quantityEnd'] != "")
		{
			$quantityEnd = $_POST['quantityEnd'];
			$WHERE = $WHERE." AND tr.quantity <= ".$quantityEnd;
		}
		if(isset($_POST['isSearch']))
		{
			$isSearch = $_POST['isSearch'];
		}
		$SQL = $SQL.$WHERE;
		$this->set('isSearch',$isSearch);
		$this->set('list_invoice',$this->Manager->query($SQL));
		$this->set('menu',$this->menu());
	}
	function wholesale(){
		$this->set('title_for_layout','Hóa đơn bán sỉ - Manager Site');
		$this->set('customers',$this->Manager->query('select c.id,c.name from customers c'));
		$SQL = "SELECT wh.id,c.`name`, c.address, c.phone, wh.total, wh.date, wh.`status`,st.`status`, wh.own
				FROM wholesale_invoices wh left join invoice_status st on wh.`status` = st.id,customers c
				WHERE wh.customer_id = c.id AND wh.delete = 0";
		$WHERE = "";
		$isSearch = 0;
		if(isset($_POST['idInvoice']) && $_POST['idInvoice'] != "")
		{
			$idInvoice = $_POST['idInvoice'];
			$WHERE = $WHERE." AND wh.id = ".$idInvoice;
		}
		if(isset($_POST['choose_cus']) && $_POST['choose_cus'] != "")
		{
			$choose_cus = $_POST['choose_cus'];
			$WHERE = $WHERE." AND wh.customer_id = ".$choose_cus;
		}
		if(isset($_POST['dateStart']) && $_POST['dateStart'] != "")
		{
			$dateStart = $_POST['dateStart'];
			$WHERE = $WHERE." AND wh.date >= '".$dateStart."'";
		}
		if(isset($_POST['dateEnd']) && $_POST['dateEnd'] != "")
		{
			$dateEnd = $_POST['dateEnd'];
			$WHERE = $WHERE." AND wh.date <= '".$dateEnd."'";
		}
		if(isset($_POST['totalStart']) && $_POST['totalStart'] != "")
		{
			$totalStart = $_POST['totalStart'];
			$WHERE = $WHERE." AND wh.total >= ".$totalStart;
		}
		if(isset($_POST['totalEnd']) && $_POST['totalEnd'] != "")
		{
			$totalEnd = $_POST['totalEnd'];
			$WHERE = $WHERE." AND wh.total <= ".$totalEnd;
		}
		if(isset($_POST['isSearch']))
		{
			$isSearch = $_POST['isSearch'];
		}
		$SQL = $SQL.$WHERE;
		$this->set('isSearch',$isSearch);
		$this->set('list_invoice',$this->Manager->query($SQL));
		$this->set('menu',$this->menu());
	}
	function retail(){
		$this->set('title_for_layout','Hóa đơn bán lẻ - Manager Site');
		$SQL = "SELECT r.id,r.cus_name,r.cus_address,r.cus_phone,r.total,r.date
			 FROM retail_invoices r 
			 WHERE r.delete = 0";
		$WHERE = "";
		$isSearch = 0;
		if(isset($_POST['idInvoice']) && $_POST['idInvoice'] != "")
		{
			$idInvoice = $_POST['idInvoice'];
			$WHERE = $WHERE." AND r.id = ".$idInvoice;
		}
		if(isset($_POST['choose_cus']) && $_POST['choose_cus'] != "")
		{
			$choose_cus = $_POST['choose_cus'];
			$WHERE = $WHERE." AND r.cus_name LIKE '%".$choose_cus."%'";
		}
		if(isset($_POST['dateStart']) && $_POST['dateStart'] != "")
		{
			$dateStart = $_POST['dateStart'];
			$WHERE = $WHERE." AND r.date >= '".$dateStart."'";
		}
		if(isset($_POST['dateEnd']) && $_POST['dateEnd'] != "")
		{
			$dateEnd = $_POST['dateEnd'];
			$WHERE = $WHERE." AND r.date <= '".$dateEnd."'";
		}
		if(isset($_POST['totalStart']) && $_POST['totalStart'] != "")
		{
			$totalStart = $_POST['totalStart'];
			$WHERE = $WHERE." AND r.total >= ".$totalStart;
		}
		if(isset($_POST['totalEnd']) && $_POST['totalEnd'] != "")
		{
			$totalEnd = $_POST['totalEnd'];
			$WHERE = $WHERE." AND r.total <= ".$totalEnd;
		}
		if(isset($_POST['isSearch']))
		{
			$isSearch = $_POST['isSearch'];
		}
		$SQL = $SQL.$WHERE;
		$this->set('isSearch',$isSearch);
		$this->set('list_invoice',$this->Manager->query($SQL));
		$this->set('menu',$this->menu());
	}
	function delivery(){
		$this->set('title_for_layout','Hóa đơn giao hàng - Manager Site');
		$SQL1 = "SELECT *
				 FROM delivery_invoices de left join cars c on de.car_id = c.id
				 WHERE de.delete = 0";
		$SQL2 = "SELECT *
				 FROM delivery_invoices de left join cars c on de.car_id = c.id
				 WHERE de.delete = 0 AND de.check = 0";
		$WHERE = "";
		$isSearch = 0;
		if(isset($_POST['idInvoice']) && $_POST['idInvoice'] != "")
		{
			$idInvoice = $_POST['idInvoice'];
			$WHERE = $WHERE." AND de.id = ".$idInvoice;
		}
		if(isset($_POST['choose_car']) && $_POST['choose_car'] != "")
		{
			$choose_car = $_POST['choose_car'];
			$WHERE = $WHERE." AND de.car_id = ".$choose_car;
		}
		if(isset($_POST['dateStart']) && $_POST['dateStart'] != "")
		{
			$dateStart = $_POST['dateStart'];
			$WHERE = $WHERE." AND de.time >= '".$dateStart."'";
		}
		if(isset($_POST['dateEnd']) && $_POST['dateEnd'] != "")
		{
			$dateEnd = $_POST['dateEnd'];
			$WHERE = $WHERE." AND de.time <= '".$dateEnd."'";
		}
		if(isset($_POST['choose_driver']) && $_POST['choose_driver'] != "")
		{
			$choose_driver = $_POST['choose_driver'];
			$WHERE = $WHERE." AND de.driver = ".$choose_driver;
		}
		if(isset($_POST['choose_transfomer1']) && $_POST['choose_transfomer1'] != "")
		{
			$choose_transfomer1 = $_POST['choose_transfomer1'];
			$WHERE = $WHERE." AND de.delivery_staff_1 = ".$choose_transfomer1." OR de.delivery_staff_2 = ".$choose_transfomer1;
		}
		if(isset($_POST['isSearch']))
		{
			$isSearch = $_POST['isSearch'];
		}
		$ORDER = " ORDER BY de.id";
		$SQL1 = $SQL1.$WHERE.$ORDER;
		$SQL2 = $SQL2.$WHERE.$ORDER;
		$this->set('isSearch',$isSearch);
		$this->set('list_invoice',$this->Manager->query($SQL1));
		$this->set('list_invoice_not_check',$this->Manager->query($SQL2));
		$this->set('list_car',$this->Manager->query('SELECT c.id,c.number
														FROM cars c'));
		$this->set('list_driver',$this->Manager->query('SELECT e.id,e.name
														FROM employees e
														WHERE e.employee_type_id = 3 or id = 4 AND e.delete = 0'));
		$this->set('list_transfomer',$this->Manager->query('SELECT e.id,e.name
														FROM employees e
														WHERE e.employee_type_id = 4 AND e.delete = 0'));
		$this->set('menu',$this->menu());
	}
	function product(){
		$this->set('title_for_layout','Quản lý sản phẩm - Manager Site');
		$this->set('productRetail',$this->Manager->query('SELECT *
													FROM products p, units u WHERE p.unit_id = u.id AND p.`delete` = 0 AND p.product_retail IS NULL'));
		$this->set('productWholesale',$this->Manager->query('SELECT *
													FROM products p , units u ,products p1 , units u1 WHERE p1.unit_id = u1.id AND p1.id = p.product_retail AND p.unit_id = u.id AND p.`delete` = 0 AND p.product_retail IS NOT NULL'));
		$this->set('types',$this->Manager->query('select * from product_types'));
		$this->set('unitsCh',$this->Manager->query('select * from units WHERE child != "" '));
		$this->set('unitsF',$this->Manager->query('select * from units WHERE father != "" '));
		$this->set('menu',$this->menu());
	}
	function product_type(){
		$this->set('title_for_layout','Quản lý loại sản phẩm - Manager Site');
		$this->set('product_type',$this->Manager->query('SELECT *
													FROM product_types pt WHERE `delete` = 0'));
		$this->set('menu',$this->menu());
	}
	function unit(){
		$this->set('title_for_layout','Quản lý đơn vị sản phẩm - Manager Site');
		$this->set('units',$this->Manager->query('select * from units u where `delete` = 0'));
		$this->set('menu',$this->menu());
	}
	function promotion(){
		$this->set('title_for_layout','Quản lý khuyến mãi - Manager Site');
		$this->set('promotion',$this->Manager->query('SELECT *
													FROM promotions pro,products p,products p1,units u,units u1 WHERE pro.sell_product = p.id AND pro.promotion_product = p1.id AND p.unit_id = u.id AND p1.unit_id = u1.id '));
		$this->set('product',$this->Manager->query('SELECT *
													FROM products p, units u WHERE p.delete = 0 AND p.unit_id = u.id AND p.quantity_retail > 0'));
		$this->set('productS',$this->Manager->query('SELECT *
													FROM products p, units u WHERE p.delete = 0 AND p.unit_id = u.id AND NOT EXISTS (SELECT * FROM promotions pro WHERE pro.sell_product = p.id)'));
		$this->set('menu',$this->menu());
	}
	function vendor(){
		$this->set('title_for_layout','Quản lý đối tác - Manager Site');
		$this->set('vendor',$this->Manager->query('SELECT *
													FROM vendors v'));
		$this->set('menu',$this->menu());
	}
	function customer(){
		$this->set('title_for_layout','Quản lý khách hàng - Manager Site');
		$this->set('customer',$this->Manager->query('SELECT *
													FROM customers c'));
		$this->set('menu',$this->menu());
	}
	function employee(){
		$this->set('title_for_layout','Quản lý nhân viên - Manager Site');
		$this->set('employee',$this->Manager->query('SELECT *
													FROM employees e LEFT JOIN users u ON e.user_id = u.id, employee_types et
													WHERE e.employee_type_id = et.id AND e.delete = 0'));
		$this->set('user',$this->Manager->query('SELECT * FROM users u WHERE u.delete = 0'));
		$this->set('employee_types',$this->Manager->query('SELECT *
													FROM employee_types et'));
		$this->set('employee_user',$this->Manager->query('SELECT *
													FROM users u WHERE NOT EXISTS (SELECT * FROM employees e WHERE e.user_id = u.id AND e.delete = 0) AND u.delete = 0'));
		$this->set('menu',$this->menu());
	}
	function other(){
		$this->set('title_for_layout','Thao tác khác - Manager Site');
		$this->set('cars',$this->Manager->query('SELECT * FROM cars c WHERE `delete` = 0'));
		$this->set('menu',$this->menu());
	}
	function printInvoice(){
		$this->layout = "print";
		if(isset($_GET['id']))
		{
			if(isset($_GET['type']))
			{
				$type = $_GET['type'];
				if ( $type == 'warehouse')
				{
					$id = $_GET['id'];
					$this->set('invoice_code','N'.$id);
					$this->set('title_for_layout','In hóa đơn nhập hàng - Manager Site');
					$query1 = 'SELECT *
                    		FROM wh_invoices wh
                    		WHERE wh.id ='.$id ;
					$query = 'SELECT p.name,u.father as unit,iv.quantity,iv.cost
			        		FROM wh_invoices_wh_wholesales iv,products p, units u 
			        		WHERE iv.product_id = p.id AND p.unit_id = u.id AND iv.wh_invoice_id='.$id ;
				}
				if ( $type == 'wholesale')
				{
					$id = $_GET['id'];
					$this->set('invoice_code','S'.$id);
					$this->set('title_for_layout','In hóa đơn bán sĩ - Manager Site');
					$query1 = 'SELECT wh.date as time,wh.total,wh.own
                			FROM wholesale_invoices wh 
                			WHERE wh.id ='.$id ;
					$query = 'SELECT p.name,u.father as unit,iv.quantity,iv.price as cost
                			FROM wholesale_invoices_wh_wholesales iv,products p, units u 
                			WHERE iv.product_id = p.id AND p.unit_id = u.id AND iv.promotion = 0 AND iv.wholesale_invoice_id='.$id ;
					$query2 = 'SELECT p.name,u.father as unit,iv.quantity,iv.price as cost
                			FROM wholesale_invoices_wh_wholesales iv,products p, units u 
                			WHERE iv.product_id = p.id AND p.unit_id = u.id AND iv.promotion = 1 AND iv.wholesale_invoice_id='.$id ;
					$result2 = $this->Manager->query($query2);
					$this->set('invoice_list_pro_info',$result2);
				}
				if ( $type == 'retail')
				{
					$id = $_GET['id'];
					$this->set('invoice_code','L'.$id);
					$this->set('title_for_layout','In hóa đơn bán lẻ - Manager Site');
					$query1 = 'SELECT wh.date as time,wh.total
                			FROM retail_invoices wh 
                			WHERE wh.id ='.$id ;
					$query = 'SELECT p.name,u.child as unit,iv.quantity,iv.price as cost
                			FROM retail_invoices_wh_retails iv,products p, units u 
                			WHERE iv.product_id = p.id AND p.unit_id = u.id AND iv.retail_invoice_id='.$id ;
				}
				if ( $type == 'delivery')
				{
					$id = $_GET['id'];
					$this->set('invoice_code','GH'.$id);
					$this->set('title_for_layout','In hóa đơn giao hang - Manager Site');
					$query1 = 'SELECT *
                			FROM delivery_invoices wh 
                			WHERE wh.id ='.$id ;
					$query = 'SELECT wh.id,c.`name`, c.address, c.phone, wh.total, wh.date,de.id, wh.status
								FROM wholesale_invoices wh,customers c, delivery_invoices_wholesale_invoices de
								WHERE wh.customer_id = c.id AND de.wholesale_invoice_id = wh.id AND de.delivery_invoice_id = '.$id;
					$query2 = 'SELECT iv.wholesale_invoice_id,p.name,u.father as unit,iv.quantity,iv.price as cost
								FROM wholesale_invoices_wh_wholesales iv,products p, units u ,delivery_invoices_wholesale_invoices de
								WHERE iv.product_id = p.id AND p.unit_id = u.id AND iv.wholesale_invoice_id = de.wholesale_invoice_id AND iv.promotion = 0 AND de.delivery_invoice_id = '.$id ;
					$result2 = $this->Manager->query($query2);
					$this->set('invoice_list_detail',$result2);
					$query3 = 'SELECT iv.wholesale_invoice_id,p.name,u.child as unit,iv.quantity,iv.price as cost
								FROM wholesale_invoices_wh_wholesales iv,products p, units u ,delivery_invoices_wholesale_invoices de
								WHERE iv.product_id = p.id AND p.unit_id = u.id AND iv.wholesale_invoice_id = de.wholesale_invoice_id AND iv.promotion = 1 AND de.delivery_invoice_id = '.$id ;
					$result3 = $this->Manager->query($query3);
					$this->set('invoice_list_pro_detail',$result3);
				}
			}
		}

		$this->set('invoice_type',$type);
		$result1 = $this->Manager->query($query1);
		$this->set('invoice_info',$result1);
		$result = $this->Manager->query($query);
		$this->set('invoice_list_info',$result);
	}
	
	function attendanceEmployee(){
		$this->layout = "print";
		$this->set('title_for_layout','Chấm công nhân viên - Manager Site');
		if(isset($_GET['month']))
		{
			$month = $_GET['month'];
			
			$this->set('attendanceEmployee',$this->Manager->query('SELECT e.name, e.employee_type_id, count(de.id) as total
				FROM employees e, delivery_invoices de
				WHERE e.employee_type_id IN (3,4) AND (e.id = de.driver OR e.id = de.delivery_staff_1 OR e.id = de.delivery_staff_2) AND e.delete = 0 AND MONTH(de.time) = '.$month.'
				GROUP BY e.id'));
		} else {
			$this->set('employee',$this->Manager->query('SELECT *
													FROM employees e, employee_types et, users u
													WHERE e.employee_type_id = et.id AND e.user_id = u.id AND e.delete = 0'));
		}
		$SQL = "SELECT *
			 FROM employees e, audit a
			 WHERE e.id = a.employee_id AND e.delete = 0";
		$WHERE = "";
		$isSearch = 0;
		if(isset($_POST['choose_employee']) && $_POST['choose_employee'] != "")
		{
			$choose_employee = $_POST['choose_employee'];
			$WHERE = $WHERE." AND e.id = ".$choose_employee;
		}
		if(isset($_POST['month']) && $_POST['month'] != "")
		{
			$month = $_POST['month'];
			$WHERE = $WHERE." AND MONTH(a.login) = ".$month;
		}
		if(isset($_POST['isSearch']))
		{
			$isSearch = $_POST['isSearch'];
		}
		$SQL = $SQL.$WHERE;
		$this->set('isSearch',$isSearch);
		$this->set('list_attendance',$this->Manager->query($SQL));
	}
	function statistic(){
		$this->set('title_for_layout','Thống kê - Manager Site');
		$this->set('menu',$this->menu());
		$this->set('products',$this->Manager->query('select * from products p, units u
														WHERE p.unit_id = u.id'));
		if(isset($_POST['statisticType']) && $_POST['statisticType'] == 2)
		{
			$product = $_POST['choose_product'];
			$this->Manager->query("BEGIN");
			if(isset($_POST['data[purchased][year]']) && $_POST['data[purchased][year]'] != ""){
				
			} else{
				$start = $_POST['startDate'];
				$end = $_POST['endDate'];
				$this->Manager->query("call make_intervals('".$start."','".$end."',1,'DAY');");
				$query = "SELECT DAY(root.time) as day, getValueBuy(DATE(root.time), ".$product.") as buy, getValueSell(DATE(root.time), ".$product.") as sell
					FROM (select DATE(interval_start) as time from time_intervals) as root"; 
				$this->set('statisticP',$this->Manager->query($query));
			}
			$this->Manager->query("COMMIT");
		}	
		
		if(isset($_POST['statisticType']) && $_POST['statisticType'] == 1)
		{
			$this->Manager->query("BEGIN");
			if(isset($_POST['data[purchased][year]']) && $_POST['data[purchased][year]'] != ""){
				$year = $_POST['data[purchased][year]'];
				$this->Manager->query("call make_intervals('".$year."-01-01','".$year."-12-31',1,'MONTH');");
				$query = "SELECT root.time, ROUND(ws.total) as ws, ROUND(re.total) as re FROM
				(select MONTH(interval_start) as time from time_intervals) as root
				LEFT JOIN
				(select MONTH(inv.date) as time, SUM(inv.total) as total
				FROM wholesale_invoices inv
				where inv.`status` = 3 and inv.`delete` = 0 and YEAR(inv.date) = ".$year."
				group by MONTH(inv.date)) as ws
				ON root.time = ws.time
				LEFT JOIN
				(select MONTH(inv.date) as time, SUM(inv.total) as total
				FROM retail_invoices inv
				where inv.`delete` = 0 and and YEAR(inv.date) = ".$year."
				group by MONTH(inv.date)) as re
				ON root.time = re.time";
				$this->set('statistic',$this->Manager->query($query));
				
			} else{
				$start = $_POST['startDate'];
				$end = $_POST['endDate'];
				$this->Manager->query("call make_intervals('".$start."','".$end."',1,'DAY');");
				$query = "SELECT DAY(root.time), ROUND(ws.total) as ws, ROUND(re.total) as re FROM 
				(select DATE(interval_start) as time from time_intervals) as root
				LEFT JOIN  
				(select DATE(inv.date) as time, SUM(inv.total) as total
				FROM wholesale_invoices inv
				where inv.`status` = 3 and inv.`delete` = 0 and DATE(inv.date) >= ".$start." and DATE(inv.date) <=".$end."
				group by DATE(inv.date)) as ws
				ON root.time = ws.time
				LEFT JOIN
				(select DATE(inv.date) as time, SUM(inv.total) as total
				FROM retail_invoices inv
				where inv.`delete` = 0 and DATE(inv.date) >= ".$start." and DATE(inv.date) <=".$end."
				group by DATE(inv.date)) as re 
				ON root.time = re.time"; 
				$this->set('statistic',$this->Manager->query($query));
			}
			$this->Manager->query("COMMIT");
		}	
	}
	//------------------------------------------------------------Code for delivery
	function choose_de_invoice() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT wh.id,c.`name`, c.address, c.phone, wh.total, wh.date,de.id, wh.status, de.wholesale_invoice_id, wh.own
				FROM wholesale_invoices wh,customers c, delivery_invoices_wholesale_invoices de
				WHERE wh.customer_id = c.id AND de.wholesale_invoice_id = wh.id AND de.delivery_invoice_id = '.$id;
		$result = $this->Manager->query($query);
		echo "<div id='tab1' class='tab_content'>
                <div class='load_page'>
                 <form id='validation'>
				<div class='tableName toolbar'>
				<table class='display data_table2 listProductDeInvoice' >
					<thead>
						<tr>
							<th><div class='th_wrapp'>Tên</div></th>
							<th><div class='th_wrapp'>Đ/chỉ</div></th>
							<th><div class='th_wrapp'>Đ/thoại</div></th>
							<th><div class='th_wrapp'>Tổng tiền</div></th>
							<th><div class='th_wrapp'>Ngày mua</div></th>
							<th><div class='th_wrapp'>Nợ</div></th>
							<th><div class='th_wrapp'></div></th>
						</tr>
					</thead>
					<tbody>";
		foreach ($result as $item)
		{
			echo "<tr class='odd gradeX' id='".$item['de']['wholesale_invoice_id']."'>";
			echo "<td>".$item['c']['name']."</td>";
			echo "<td>".$item['c']['address']."</td>";
			echo "<td>".$item['c']['phone']."</td>";
			echo "<td class='formatMoney'>".$item['wh']['total']."</td>";
			echo "<td>".date('d/m/Y H:i',strtotime($item['wh']['date']))."</td>";
			echo "<td><div class='formatMoney'>".$item['wh']['own']."</div>"; if ($item['wh']['status'] != 3 && $item['wh']['own'] > 0) echo"<input name='cash' id='cash' class='validate[custom[onlyNumberSp]]'/>";
			echo "</td><td >
				<span class='info' >
                         <a title='Thông tin' >
                                  <img src='".$this->webroot."img/icon/icon_edit.png' >
                          </a>
                  </span>
      			 <input type='checkbox' name='status' id='checkNormal' class='checkDe' ";if ($item['wh']['status'] == 3) echo "checked"; echo "/>
      		
                 <span class='delete' >
                         <a title='Delete' >
                                  <img src='".$this->webroot."img/icon/icon_delete.png' >
                          </a>
                  </span>
                                  		
            </td></tr>";
		}
		echo "</tbody></table></div></form>";
		$check = $_GET["check"];
		if($check == 0){
			echo "	<a class='uibutton icon edit isCheck' id='$id'>Đã kiểm tra</a>
					<a class='uibutton icon forward updateInvoice' id='$id'>Cập nhật</a>
					<a class='uibutton icon add addNewWhInvoice'>Thêm mới</a>";

			$query = 'SELECT wh.id,c.`name`, c.address, c.phone, wh.total, wh.date
						FROM wholesale_invoices wh,customers c
						WHERE wh.customer_id = c.id AND wh.status = 1' ;
			$result = $this->Manager->query($query);
			echo" <div class='newWhInvoice'>
					<h4>Hóa đơn chưa giao</h4>
					<div class='clear'></div>
				<div class='content'>
			        <form>
			                            		<div class='tableName'>
													<table class='display data_table2 listWhInvoiceTransfer1' >
														<thead>
															<tr>
																<th><div class='th_wrapp'>Tên</div></th>
																<th><div class='th_wrapp'>Địa chỉ</div></th>
																<th><div class='th_wrapp'>Điện thoại</div></th>
																<th><div class='th_wrapp'>Tổng tiền</div></th>
																<th><div class='th_wrapp'>Ngày mua</div></th>
																<th><div class='th_wrapp'></div></th>
																<th><div class='th_wrapp'></div></th>
															</tr>
														</thead>
														<tbody>";

			foreach ($result as $item)
			{
				echo "<tr class='odd gradeX' id='".$item['wh']['id']."'>
										      					<td class='WhInvoice'>".$item['c']['name']."</td>
										      					<td>".$item['c']['address']."</td>
										      					<td>".$item['c']['phone']."</td>
										      					<td class='formatMoney'>". $item['wh']['total']."</td>
										      					<td>".date('d/m/Y H:i',strtotime($item['wh']['date']))."</td>
								      							<td></td>
								      							<td >
									      							<span class='info' >
													                         <a title='Info' >
													                                  <img src='".$this->webroot."img/icon/icon_edit.png' >
													                          </a>
													                  </span>
													      			 <input type='checkbox' name='status' id='checkNormal'/>
													                 <span class='delete' >
													                         <a title='Delete' >
													                                  <img src='".$this->webroot."img/icon/icon_delete.png' >
													                          </a>
													                  </span>
													            </td>
										      					</tr>";
			}
			echo"</tbody>
												</table>
								            </div>
										</form>
			         </div>
					<div class='buttonNewWhInvoice'>
						<a class='uibutton new_WhInvoice'><span class='ico gray checkmark2 '></span>Lưu</a>
						<a class='uibutton special cancel'><span class='ico gray cross'></span>Hủy</a>
					</div>
				</div>";
		}
		echo"</div></div>";
		$query = 'SELECT r.id,r.cus_name,r.cus_address,r.cus_phone,r.total,r.date,de.id
					FROM retail_invoices r, delivery_invoices_retail_invoices de
					WHERE de.retail_invoice_id = r.id AND de.delivery_invoice_id ='.$id ;
		$result = $this->Manager->query($query);
		echo "<div id='tab2' class='tab_content'>
                <div class='load_page'>
                 <form>
				<div class='tableName toolbar'>
				<table class='display data_table2 listProductDeInvoice' >
					<thead>
						<tr>
							<th><div class='th_wrapp'>Tên</div></th>
							<th><div class='th_wrapp'>Địa chỉ</div></th>
							<th><div class='th_wrapp'>Điện thoại</div></th>
							<th><div class='th_wrapp'>Tổng cộng</div></th>
							<th><div class='th_wrapp'>Ngày mua</div></th>
							<th><div class='th_wrapp'>Đã trả</div></th>
							<th><div class='th_wrapp'></div></th>
						</tr>
					</thead>
					<tbody>";
		foreach ($result as $item)
		{
			echo "<tr class='odd gradeX' id='".$item['de']['id']."'>";
			echo "<td>".$item['r']['cus_name']."</td>";
			echo "<td>".$item['r']['cus_address']."</td>";
			echo "<td>".$item['r']['cus_phone']."</td>";
			echo "<td class='formatMoney'>".$item['r']['total']."</td>";
			echo "<td>".date('d/m/Y H:i',strtotime($item['r']['date']))."</td>";
			echo "<td><input name='cash' id='cash' /></td>";
			echo "<td >
      			 <span class='tip' >
                         <a title='Edit' >
                                  <img src='".$this->webroot."img/icon/icon_edit.png' >
                          </a>
                 </span>
                 <span class='tip' >
                         <a title='Delete' >
                                  <img src='".$this->webroot."img/icon/icon_delete.png' >
                          </a>
                  </span>
            </td></tr>";
		}
		echo "</tbody></table></div></form></div></div>";
			
	}
	//------------------------------------------------------------Code for retail
	function choose_re_invoice() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT p.`name`,re.price,re.quantity,re.id FROM products p, retail_invoices_wh_retails re WHERE re.product_id = p.id AND re.retail_invoice_id = '.$id ;
		$result = $this->Manager->query($query);
		echo "<div class='tableName'>
				<table class='display data_table2 listProductReInvoice' >
					<thead>
						<tr>
							<th><div class='th_wrapp'>Hàng hóa</div></th>
							<th><div class='th_wrapp'>Số lượng</div></th>
							<th><div class='th_wrapp'>Giá tiền</div></th>
							<th><div class='th_wrapp'>Quản lý</div></th>
						</tr>
					</thead>
					<tbody>";
		foreach ($result as $item)
		{
			echo "<tr class='odd gradeX' id='".$item['re']['id']."'>";
			echo "<td class='editName'><div class='old_name'>".$item['p']['name']."</div>
      			<input id='". $item['re']['id']."_edit_n' value ='". $item['p']['name']."'class='validate[required] tmp_name' style='display: none'/>
      		</td>";
			echo "<td class='editQuantity'><div class='old_quantity'>".$item['re']['quantity']."</div>
      			<input id='". $item['re']['id']."_edit_q' value ='". $item['re']['quantity']."'class='validate[required] tmp_quantity' style='display: none'/>
      		</td>";
			echo "<td class='editPrice'><div class='old_price formatMoney'>".$item['re']['price']."</div>
      			<input id='". $item['re']['id']."_edit_c' value ='". $item['re']['price']."'class='validate[required] tmp_price' style='display: none'/>
      		</td>";
			echo "<td >
                                <span class='btnEdit'>
                                      <a  title='Edit' >
                                           <img src='".$this->webroot ."img/icon/color_18/pencil.png' >
                                      </a>
                                 </span> 
                                 <span class='tip btnDelete' >
                                       <a title='Delete'  >
                                           <img src='".$this->webroot."img/icon/color_18/delete.png' >
                                       </a>
                                </span> 
                                <span class='btnSave' style='display: none'>
                                      <a  title='Save' >
                                           <img src='". $this->webroot ."img/icon/color_18/checkmark2.png' >
                                      </a>
                                 </span>
                                 <span class='btnCancel' style='display: none'>
                                      <a  title='Cancel'>
                                           <img src='". $this->webroot ."img/icon/color_18/cross.png' >
					                                      </a>
					                                 </span>
					                            </td></tr>";
		}
		echo "</tbody></table></div>";
	}
	//------------------------------------------------------------Code for wholesale
	function choose_ws_invoice() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT p.`name`,ws.price,ws.quantity,ws.wholesale_invoice_id,ws.id, p.quantity_wholesale
					FROM products p, wholesale_invoices_wh_wholesales ws
					WHERE ws.product_id = p.id AND ws.promotion = 0 AND ws.wholesale_invoice_id = "'.$id.'"
					GROUP BY p.`name`,ws.price,ws.quantity,ws.wholesale_invoice_id' ;
		$result = $this->Manager->query($query);
		echo "<div id='tab1' class='tab_content'>
                <div class='load_page'>
                 <form id='validation'>
				<div class='tableName toolbar'>
				<table class='display data_table2 listProductWsInvoice' >
					<thead>
						<tr>
							<th><div class='th_wrapp'>Hàng hóa</div></th>
							<th><div class='th_wrapp'>Số lượng</div></th>
							<th><div class='th_wrapp'>Giá tiền</div></th>
							<th><div class='th_wrapp'>Quản lý</div></th>
						</tr>
					</thead>
					<tbody>";
		foreach ($result as $item)
		{
			echo "<tr class='odd gradeX'  id='".$item['ws']['id']."_save'>";
			echo "<td class='editName'><div class='old_name'>".$item['p']['name']."</div>
      			<input id='". $item['ws']['wholesale_invoice_id']."_edit_n' value ='". $item['p']['name']."'class='validate[required] tmp_name' style='display: none'/>
      		</td>";
			echo "<td class='editQuantity'><div class='old_quantity'>".$item['ws']['quantity']."</div>
      			<input id='". $item['ws']['wholesale_invoice_id']."_edit_q' value ='". $item['ws']['quantity']."'class='validate[required,custom[number],max[".$item['p']['quantity_wholesale']."]] tmp_quantity' style='display: none; width: 30px;'/>
      		</td>";
			echo "<td class='editPrice'><div class='old_price formatMoney'>".$item['ws']['price']."</div>
      			<input id='". $item['ws']['wholesale_invoice_id']."_edit_c' value ='". $item['ws']['price']."'class='validate[required,custom[number]] tmp_price' style='display: none'/>
      		</td>";
			echo "<td >
                                <span class='btnEdit'>
                                      <a  title='Edit' >
                                           <img src='".$this->webroot ."img/icon/color_18/pencil.png' >
                                      </a>
                                 </span> 
                                 <span class='tip btnDelete' >
                                       <a title='Delete'  >
                                           <img src='".$this->webroot."img/icon/color_18/delete.png' >
                                       </a>
                                </span> 
                                <span class='btnSave' style='display: none'>
                                      <a  title='Save' >
                                           <img src='". $this->webroot ."img/icon/color_18/checkmark2.png' >
                                      </a>
                                 </span>
                                 <span class='btnCancel' style='display: none'>
                                      <a  title='Cancel'>
                                           <img src='". $this->webroot ."img/icon/color_18/cross.png' >
					                                      </a>
					                                 </span>
					                            </td></tr>";
		}
		echo "</tbody></table></div></form></div></div>";
		$query = 'SELECT p.`name`,ws.price,ws.quantity,ws.wholesale_invoice_id, ws.id
					FROM products p, wholesale_invoices_wh_wholesales ws
					WHERE ws.product_id = p.id AND ws.promotion = 1 AND ws.wholesale_invoice_id = "'.$id.'"
					GROUP BY p.`name`,ws.price,ws.quantity,ws.wholesale_invoice_id' ;
		$result = $this->Manager->query($query);
		echo "<div id='tab2' class='tab_content'>
                <div class='load_page'>
                 <form>
				<div class='tableName toolbar'>
				<table class='display data_table2 listProductWsInvoice' >
					<thead>
						<tr>
							<th><div class='th_wrapp'>Hàng hóa</div></th>
							<th><div class='th_wrapp'>Số lượng</div></th>
							<th><div class='th_wrapp'>Giá tiền</div></th>
							<th><div class='th_wrapp'>Quản lý</div></th>
						</tr>
					</thead>
					<tbody>";
		foreach ($result as $item)
		{
			echo "<tr class='odd gradeX' id='".$item['ws']['id']."_save'>";
			echo "<td>".$item['p']['name']."</td>";
			echo "<td class='formatMoney'>".$item['ws']['price']."</td>";
			echo "<td>".$item['ws']['quantity']."</td>";
			echo "<td >
 					<span class='tip btnDelete' >
                                       <a title='Delete'  >
                                           <img src='".$this->webroot."img/icon/color_18/delete.png' >
                                       </a>
                                </span> 
            </td></tr>";
		}
		echo "</tbody></table></div></form></div></div>";
	}
	//------------------------------------------------------------Code for retail_wh_status
	function edit_price_cost_re() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$price = $_GET["price"];
		try {
			$this->Manager->query('UPDATE products SET price_retail = '.$price.' WHERE id =' .$id);
			return true;
		}
		catch (Exception $e)	{
			return false;
		}
	}
	//------------------------------------------------------------Code for wholesale_wh_status
	function edit_price_cost_wh() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$price = $_GET["price"];
		$cost = $_GET["cost"];
		if($this->Manager->query('UPDATE wh_wholesales SET price = '.$price.',cost = '.$cost.' WHERE id =' .$id))
		{
			echo 'Cập nhật giá thành công';
		}
		else
		{
			echo 'Cập nhật giá không thành công';
		}
	}
	//------------------------------------------------------------Code for retail-invoice
	function choose_product_retail() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT * FROM products WHERE  id='.$id;
		$result = $this->Manager->query($query);
		$return = '';
		foreach ($result as $item)
		{
			$return = $return. "<div class='section listP nameListPWh'>
					<div class='nameListProduct'>".$item['products']['name']."</div></div>";
			$return = $return."
				<div class='section listP priceListPWh'>
					<div id= '".$item['products']['id']."_price'>".$item['products']['price_retail']."</div>
				</div>
				<div class='section numericonly listP countListPWh'>
					<div>
					<span>(".$item['products']['quantity_retail'].")</span>	
					<input class='validate[required,min[1]] large onChange' type='text' id='".$item['products']['id']."_quantity'>
					</div>
				</div>
				<div class='section listP'>
					<a class='uibutton special remove_product' id='".$item['products']['id']."_remove'>Xóa</a>
				</div>
				<input type ='hidden' id='".$item['products']['id']."_sum' class='sumEach'/>";
		}
		echo $return;
	}

	function create_retail_invoice() {
		//lay danh sach id, so luong, gia
		$this->autoRender=false;
		$ids = $_GET["list_id"];
		$list_quantity = $_GET["list_quantity"];
		$ids = substr($ids, 0, strlen($ids) -1 );
		$list_quantity = substr($list_quantity, 0, strlen($list_quantity) -1 );
		$cus_name = $_GET["cus_name"];
		$cus_phone = $_GET["cus_phone"];
		$cus_address = $_GET["cus_address"];
		//Tao cac mang
		$id_array = explode(',', $ids);
		$quantity_array = explode(',', $list_quantity);
		$this->Manager->query("BEGIN");
		try {
			//Them mot dong vao ban wh_invoices
			$employee_id = $this->Manager->query("SELECT e.id FROM employees e JOIN users u ON e.user_id = u.id WHERE u.id =".$this->Auth->user("id"));
			$this->Manager->query('INSERT INTO retail_invoices(date,cus_name,employee_id,cus_address,cus_phone) VALUES (NOW(),"'.$cus_name.'",'.$employee_id[0]["e"]["id"].',"'.$cus_address.'","'.$cus_phone.'")');

			//Lay ma hoa don moi tao
			$get_invoice = $this->Manager->query("SELECT LAST_INSERT_ID()");
			$id_invoice = '';
			foreach ($get_invoice as $item)
			{
				$id_invoice = $item['0']['LAST_INSERT_ID()'];
			}
			$sum ='';
			//Them chi tiet cua hoa don
			for ($i=0; $i < count($id_array); $i++)
			{
				$quantity = $quantity_array[$i];
				$id = $id_array[$i];
				$price ='';
				$quantity_wh ='';
				$query = 'SELECT price_retail,quantity_retail FROM products WHERE id='.$id;
				$result = $this->Manager->query($query);
				foreach ($result as $item)
				{
					$price = $item['products']['price_retail'];
					$quantity_wh = $item['products']['quantity_retail'];
				}
				$sum = $sum + $quantity * $price;
				$rest = $quantity_wh - $quantity;
				$this->Manager->query("UPDATE products SET quantity_retail = '".$rest."' WHERE id='".$id."' ");
				$this->Manager->query("INSERT retail_invoices_wh_retails(retail_invoice_id,product_id,quantity,price)
											VALUES ('".$id_invoice."','".$id."','".$quantity."','".$price."')");
			}
			$this->Manager->query("UPDATE retail_invoices SET total = '".$sum."' WHERE id='".$id_invoice."' ");
			$this->Manager->query("COMMIT");
			return $id_invoice;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}
	//------------------------------------------------------------Code for warehouse
	function choose_wh_invoice() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT * FROM wh_invoices_wh_wholesales wh,products p WHERE wh.product_id = p.id AND wh.wh_invoice_id='.$id ;
		$result = $this->Manager->query($query);
		echo "<div class='tableName'>
				<table class='display data_table2 listProductWhInvoice' >
					<thead>
						<tr>
							<th><div class='th_wrapp'>Hàng hóa</div></th>
							<th><div class='th_wrapp'>Số lượng</div></th>
							<th><div class='th_wrapp'>Giá tiền</div></th>
							<th><div class='th_wrapp'>Quản lý</div></th>
						</tr>
					</thead>
					<tbody>";
		foreach ($result as $item)
		{
			echo "<tr class='odd gradeX' id='".$item['wh']['id']."'>";

			echo "<td class='editName'><div class='old_name'>".$item['p']['name']."</div>
      			<input id='". $item['wh']['id']."_edit_n' value ='". $item['p']['name']."'class='validate[required] tmp_name' style='display: none'/>
      		</td>";
			echo "<td class='editQuantity'><div class='old_quantity'>".$item['wh']['quantity']."</div>
      			<input id='". $item['wh']['id']."_edit_q' value ='". $item['wh']['quantity']."'class='validate[required] tmp_quantity' style='display: none'/>
      		</td>";
			echo "<td class='editCost'><div class='old_cost formatMoney'>".$item['wh']['cost']."</div>
      			<input id='". $item['wh']['id']."_edit_c' value ='". $item['wh']['cost']."'class='validate[required] tmp_cost' style='display: none'/>
      		</td>";
			echo "<td >
                                <span class='btnEdit'>
                                      <a  title='Edit' >
                                           <img src='".$this->webroot ."img/icon/color_18/pencil.png' >
                                      </a>
                                 </span>
                                 <span class='tip btnDelete' >
                                       <a title='Delete'  >
                                           <img src='".$this->webroot."img/icon/color_18/delete.png' >
                                       </a>
                                </span>
                                <span class='btnSave' style='display: none'>
                                      <a  title='Save' >
                                           <img src='". $this->webroot ."img/icon/color_18/checkmark2.png' >
                                      </a>
                                 </span>
                                 <span class='btnCancel' style='display: none'>
                                      <a  title='Cancel'>
                                           <img src='". $this->webroot ."img/icon/color_18/cross.png' >
					                                      </a>
					                                 </span>
					                            </td></tr>";
		}
		echo "</tbody></table></div>";
	}


	function choose_warehouse_invoice($id) {
		$this->autoRender=false;
		$query = 'SELECT * FROM wh_invoices_wh_wholesales wh,products p WHERE wh.product_id = p.id AND wh.wh_invoice_id='.$id ;
		$result = $this->Manager->query($query);
		echo "<div class='tableName'>
				<table class='display data_table2 listProductWhInvoice' >
					<thead>
						<tr>
							<th><div class='th_wrapp'>Hàng hóa</div></th>
							<th><div class='th_wrapp'>Số lượng</div></th>
							<th><div class='th_wrapp'>Giá tiền</div></th>
							<th><div class='th_wrapp'>Quản lý</div></th>
						</tr>
					</thead>
					<tbody>";
		foreach ($result as $item)
		{
			echo "<tr class='odd gradeX' id='".$item['wh']['id']."'>";
			echo "<td>".$item['p']['name']."</td>";
			echo "<td>".$item['wh']['quantity']."</td>";
			echo "<td class='formatMoney'>".$item['wh']['cost']."</td>";
			echo "<td >
      			 <span class='tip' >
                         <a title='Edit' >
                                  <img src='".$this->webroot."img/icon/icon_edit.png' >
                          </a>
                 </span> 
                 <span class='tip' >
                         <a title='Delete' >
                                  <img src='".$this->webroot."img/icon/icon_delete.png' >
                          </a>
                  </span> 
            </td></tr>";
		}
		echo "</tbody></table></div>";
	}

	//------------------------------------------------------------Code for transfer_invoice
	function choose_product_transfer() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$quantity = $_GET["quantity"];
		$query = 'SELECT * FROM products WHERE id='.$id;
		$result = $this->Manager->query($query);
		foreach ($result as $item)
		{
			echo "<div class='section listP nameListPTr'>
					<div class='nameListProduct'>".$item['products']['name']."</div>
				</div>
				<div class='section numericonly listP countListPTr'>
					<div>
						<input class='validate[required,max[".$quantity."],min[1]] large' type='text' id='".$id."_quantity'>
					</div>
				</div>
				<div class='section listP'>
					<a class='uibutton special remove_product' id='".$id."_remove'>Xóa</a>
				</div>";
		}
	}
	function create_transfer_invoice(){
		$this->autoRender=false;
		$this->Manager->query('BEGIN');
		try {
			$ids = $_GET["list_id"];
			$list_quantity = $_GET["list_quantity"];
			$list_quantity_tr = $_GET["list_quantity_tr"];
			$ids = substr($ids, 0, strlen($ids) -1 );
			$list_quantity = substr($list_quantity, 0, strlen($list_quantity) -1 );
			$list_quantity_tr = substr($list_quantity_tr, 0, strlen($list_quantity_tr) -1 );
			$id_array = explode(',', $ids);
			$quantity_array = explode(',', $list_quantity);
			$quantity_tr_array = explode(',', $list_quantity_tr);
			for ($i=0; $i < count($id_array); $i++)
			{
				$quantity_tr = $quantity_tr_array[$i];
				$quantity = $quantity_array[$i];
				$id = $id_array[$i];
				$this->Manager->query("INSERT INTO transfer_invoices(product_id,time,quantity) VALUES ('".$id."',NOW(),'".$quantity_tr."') ");
				$quantity_new = $quantity - $quantity_tr;
				$this->Manager->query("UPDATE products SET quantity_wholesale = '".$quantity_new."' WHERE id='".$id."' ");
				$this->Manager->query("UPDATE products p, units u
											SET p.quantity_retail = p.quantity_retail + ".$quantity_tr."*u.`convert`
											WHERE p.unit_id = u.id AND p.id='".$id."' ");
			}
			$this->Manager->query('COMMIT');
			echo true;
		}
		catch (Exception $e){
			$this->Manager->query('ROLLBACK');
			echo false;
		}
	}
	//------------------------------------------------------------Code for warehouse_invoice
	function search_vendor() {
		$this->autoRender=false;
		$q = $_GET["q"];
		if ($q == '')
		{
			echo "Không có kết quả nào";
		}
		else
		{
			$query = 'SELECT name,id FROM vendors WHERE name LIKE \'%'.$q.'%\' LIMIT 0,10';
			$result = $this->Manager->query($query);
			$count = 0;
			foreach ($result as $item)
			{
				echo "<a id='".$item['vendors']['id']."_vendor' class='choose_vendor'>".$item['vendors']['name']."</a></br>";
				$count += 1;
			}
			if ($count == 0)
			{
				echo "Không có kết quả nào";
			}
		}
	}

	function choose_vendor() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT * FROM vendors WHERE id='.$id;
		$result = $this->Manager->query($query);
		foreach ($result as $item)
		{
			echo "<h4> Thông tin đối tác</h4>
				  <ul class='list_arrow'>";
			echo "<li><span class='ico gray cabinet vendor_id' id='".$item['vendors']['id']."'></span><label>Tên cửa hàng: </label><div class='infoVendor'>".$item['vendors']['store']."</div></li></br>";
			echo "<li><span class='ico gray user'></span><label>Chủ cửa hàng: </label><div class='infoVendor'>".$item['vendors']['name']."</div></li></br>";
			echo "<li><span class='ico gray location'></span><label>Địa chỉ: </label><div class='infoVendor'>".$item['vendors']['address']."</div></li></br>";
			echo "<li><span class='ico gray phone'></span><label>Điện thoại bàn: </label><div class='infoVendor'>".$item['vendors']['phone']."</div></li></br>";
			echo "<li><span class='ico gray phone'></span><label>Điện thoại di động: </label><div class='infoVendor'>".$item['vendors']['mobile']."</div></li></br>
				  </ul>";
		}
	}


	function search_product() {
		$this->autoRender=false;
		$q = $_GET["q"];
		if ($q == '')
		{
			echo "Không có kết quả nào";
		}
		else
		{
			$query = 'SELECT name,id FROM products WHERE name LIKE \'%'.$q.'%\' LIMIT 0,10';
			$result = $this->Manager->query($query);
			$count = 0;
			foreach ($result as $item)
			{
				echo "<a id='".$item['products']['id']."_product' class='choose_product'>".$item['products']['name']."</a></br>";
				$count += 1;
			}
			if ($count == 0)
			{
				echo "Không có kết quả nào";
			}
		}
	}


	function choose_product() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT * FROM products WHERE id='.$id;
		$result = $this->Manager->query($query);
		foreach ($result as $item)
		{
			echo "<div class='section listP nameListP'>
					<div class='nameListProduct'>".$item['products']['name']."</div>
				</div>
				<div class='section numericonly listP priceListP'>
					<div>
						<input class='validate[required,custom[onlyNumberSp]] large onChange' type='text' id='".$item['products']['id']."_cost'>
					</div>
				</div>
				<div class='section numericonly listP countListP'>
					<div>
						<input class='validate[required,custom[onlyNumberSp]] large onChange focusBarcode' type='text' id='".$item['products']['id']."_quantity'>
					</div>
				</div>
				<input type ='hidden' id='".$item['products']['id']."_sum' class='sumEach'/>
				<div class='section listP'>
					<a class='uibutton special remove_product' id='".$item['products']['id']."_remove'>Xóa</a>
				</div>";
		}
	}


	function create_warehouse_invoice() {
		//lay danh sach id, so luong, gia
		$this->autoRender=false;
		$ids = $_GET["list_id"];
		$list_quantity = $_GET["list_quantity"];
		$list_price = $_GET["list_price"];
		$ids = substr($ids, 0, strlen($ids) -1 );
		$list_quantity = substr($list_quantity, 0, strlen($list_quantity) -1 );
		$list_price = substr($list_price, 0, strlen($list_price) -1 );
		$vendor_id = $_GET["vendor"];

		//Tao cac mang
		$id_array = explode(',', $ids);
		$quantity_array = explode(',', $list_quantity);
		$price_array = explode(',', $list_price);
		$return = '';
		$this->Manager->query("BEGIN");
		try {
			//Them mot dong vao ban wh_invoices
			$this->Manager->query('INSERT INTO wh_invoices(vendor_id,time) VALUES ('.$vendor_id.', NOW())');

			//Lay ma hoa don moi tao
			$get_invoice = $this->Manager->query("SELECT id
									FROM wh_invoices WHERE vendor_id = '".$vendor_id."' 
									ORDER BY id DESC LIMIT 0,1");
			$id_invoice = '';
			foreach ($get_invoice as $item)
			{
				$id_invoice = $item['wh_invoices']['id'];
			}
			$sum ='';
			$id_wh = '';
			//Them chi tiet cua hoa don
			for ($i=0; $i < count($id_array); $i++)
			{
				$quantity = $quantity_array[$i];
				$price = $price_array[$i];
				$id = $id_array[$i];
				$sum = $sum + $quantity* $price;
				//Kiem tra san pham da co trong kho va gia nhap co bang nhau hay khong
				$get_wholesale_id = $this->Manager->query("select detail.wh_wholesale_id as wh_wholesale_id, k.quantity as quantity
							from wh_wholesales k, wh_invoices_wh_wholesales detail
							where k.id = detail.wh_wholesale_id and detail.product_id =".$id." and k.cost = '".$price."'
							GROUP BY detail.wh_wholesale_id, k.quantity");

				//Neu khong co san pham nao trong kho hoac co san pham nhung khac gia
				if (count($get_wholesale_id) == 0)
				{
					//Tao moi mot dong trong kho si
					$this->Manager->query("INSERT INTO wh_wholesales(cost,quantity,product_id) VALUES ('".$price."','".$quantity."','".$id."') ");

					//Lay ma kho moi tao
					$get_wh_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
					foreach ($get_wh_id as $item)
					{
						if ($id_wh == '')
						{
							$id_wh = $item['0']['LAST_INSERT_ID()'];
						}
						else
						{
							$id_wh = $id_wh + 1;
						}
					}
					//Them dong moi vao chi tiet hoa don
					$this->Manager->query("INSERT INTO wh_invoices_wh_wholesales(wh_wholesale_id,wh_invoice_id,product_id,quantity,cost)
											VALUES ('".$id_wh."','".$id_invoice."','".$id."','".$quantity."','".$price."') ");	
				}
				//Neu co san pham trong kho va cung gia
				else
				{
					//cap nhat lai so luong hang trong kho
					foreach ( $get_wholesale_id as $item)
					{
						$wholesale_id = $item['detail']['wh_wholesale_id'];
						$quantity_old = $item['k']['quantity'];
						$quantity_new = $quantity + $quantity_old;
						$this->Manager->query("UPDATE wh_wholesales SET quantity = '".$quantity_new."' WHERE id='".$wholesale_id."' ");
						$this->Manager->query("INSERT INTO wh_invoices_wh_wholesales(wh_wholesale_id,wh_invoice_id,product_id,quantity,cost)
											VALUES ('".$wholesale_id."','".$id_invoice."','".$id."','".$quantity."','".$price."') ");
					}
				}
				$this->Manager->query("UPDATE products SET quantity_wholesale = quantity_wholesale + ".$quantity." where id=".$id);
			}
			$this->Manager->query("UPDATE wh_invoices SET total = '".$sum."' WHERE id='".$id_invoice."' ");
			$this->Manager->query("COMMIT");
			echo $id_invoice;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}


	function new_vendor() {
		$this->autoRender=false;
		$name = $_GET["name"];
		$store = $_GET["store"];
		$mobile = $_GET["mobile"];
		$phone = $_GET["phone"];
		$address = $_GET["address"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("INSERT INTO vendors(name,store,address,mobile,phone)
									VALUES ('".$name."','".$store."','".$address."','".$mobile."','".$phone."')");

			$id_vendor = '';
			$get_vendor_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_vendor_id as $item)
			{
				$id_vendor = $item['0']['LAST_INSERT_ID()'];
			}
			$this->Manager->query("COMMIT");
			echo $id_vendor;
		}
		catch(Exception $e){
			$this->Manager->query("ROLLBACK");
			echo false;
		}

	}


	function new_product() {
		$this->autoRender=false;
		$name = $_GET["name"];
		$unit = $_GET["unit"];
		$type = $_GET["type"];
		$barcode = $_GET["barcode"];
		$this->Manager->query("BEGIN");
		try
		{
			$this->Manager->query("INSERT INTO products(name,product_type_id,barcode,unit_id)
									VALUES ('".$name."','".$type."','".$barcode."','".$unit."')");
			$id_product = '';
			$get_product_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_product_id as $item)
			{
				$id_product = $item['0']['LAST_INSERT_ID()'];
			}
			$this->Manager->query("COMMIT");
			echo $id_product;
		}
		catch  (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}



	//------------------------------------------------------------Code for wholesale_invoice
	function search_cus() {
		$this->autoRender=false;
		$q = $_GET["q"];
		if ($q == '')
		{
			echo "Không có kết quả nào";
		}
		else
		{
			$query = 'SELECT name,id FROM customers WHERE name LIKE \'%'.$q.'%\' LIMIT 0,10';
			$result = $this->Manager->query($query);
			$count = 0;
			foreach ($result as $item)
			{
				echo "<a id='".$item['customers']['id']."_cus' class='choose_cus'>".$item['customers']['name']."</a></br>";
				$count += 1;
			}
			if ($count == 0)
			{
				echo "Không có kết quả nào";
			}
		}
	}


	function choose_cus() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT * FROM customers WHERE id='.$id;
		$result = $this->Manager->query($query);
		foreach ($result as $item)
		{
			echo "<h4> Thông tin khách hàng</h4>
				  <ul class='list_arrow'>";
			echo "<li><span class='ico gray cabinet cus_id' id='".$item['customers']['id']."'></span><label>Tên cửa hàng: </label><div class='infoVendor'>".$item['customers']['store']."</div></li></br>";
			echo "<li><span class='ico gray user'></span><label>Chủ cửa hàng: </label><div class='infoVendor'>".$item['customers']['name']."</div></li></br>";
			echo "<li><span class='ico gray location'></span><label>Địa chỉ: </label><div class='infoVendor'>".$item['customers']['address']."</div></li></br>";
			echo "<li><span class='ico gray phone'></span><label>Điện thoại bàn: </label><div class='infoVendor'>".$item['customers']['phone']."</div></li></br>";
			echo "<li><span class='ico gray phone'></span><label>Điện thoại di động: </label><div class='infoVendor'>".$item['customers']['mobile']."</div></li></br>
				  </ul>";
		}
	}


	function choose_product_wholesale() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$query = 'SELECT p.name, p.id, p.quantity_wholesale, u.father, p.price_wholesale FROM products p , units u WHERE p.unit_id = u.id AND p.id='.$id;
		$result = $this->Manager->query($query);
		$return = '';
		foreach ($result as $item)
		{
			$return = $return. "<div class='section listP nameListPWh'>
					<div class='nameListProduct'>".$item['p']['name']."</div></div>";
			$return = $return."<div class='section listP totalListPWh'>
									<div>
										".$item['p']['quantity_wholesale']." ".$item['u']['father']."
									</div>
								</div> ";
			$return = $return."<div class='section listP priceListPWh'>
								<input id='".$item['p']['id']."_price' class='large onChange' type='text' value='".$item['p']['price_wholesale']."'>
							</div>";
			$return = $return."
				<div class='section numericonly listP countListPWh'>
					<div>
						<input class='validate[required,custom[number],max[".$item['p']['quantity_wholesale']."]] large onChange focusBarcode' type='text' id='".$item['p']['id']."_quantity'>
					</div>
				</div>
				<div class='section numericonly listP promotionListPWh'>
					<div>";
			$query = 'SELECT pro.promotion_quantity, pro.sell_product,pro.sell_quantity, u.child, p.`name`, u.father
					  FROM promotions pro join products p on pro.promotion_product = p.id
										join units u on p.unit_id = u.id
				      WHERE quota > 0 AND sell_product ='.$id;
			$result = $this->Manager->query($query);
			if (sizeof($result) > 0) {
				foreach ($result as $promotion){
					$return = $return."Mua ".$promotion["pro"]["sell_quantity"]." ".$promotion["u"]["father"]
					." tặng ".$promotion["pro"]["promotion_quantity"]." ".$promotion["u"]["child"]
					." ".$promotion["p"]["name"];
				};
			}
			$return = $return."</div>
				</div>
				<div class='section listP'>
					<a class='uibutton special remove_product' id='".$item['p']['id']."_remove'>Xóa</a>
				</div>
				<input type ='hidden' id='".$item['p']['id']."_sum' class='sumEach'/>";
		}
		echo $return;
	}




	function create_wholesale_invoice() {
		//lay danh sach id, so luong, gia
		$this->autoRender=false;
		$ids = $_GET["list_id"];
		$list_quantity = $_GET["list_quantity"];
		$list_promotion = $_GET["list_promotion"];
		$list_price = $_GET["list_price"];
		$amount = $_GET["amount"];
		$ids = substr($ids, 0, strlen($ids) -1 );
		$list_quantity = substr($list_quantity, 0, strlen($list_quantity) -1 );
		$list_promotion = substr($list_promotion, 0, strlen($list_promotion) -1 );
		$list_price = substr($list_price, 0, strlen($list_price) -1 );
		$cus_id = $_GET["cus"];

		//Tao cac mang
		$id_array = explode(',', $ids);
		$quantity_array = explode(',', $list_quantity);
		$promotion_array = explode(',', $list_promotion);
		$price_array = explode(',', $list_price);
		$return = '';
		$this->Manager->query('BEGIN');
		try {
			//Them mot dong vao ban wh_invoices
			$employee_id = $this->Manager->query("SELECT e.id FROM employees e JOIN users u ON e.user_id = u.id WHERE u.id =".$this->Auth->user("id"));
			$this->Manager->query('INSERT INTO wholesale_invoices(customer_id,date,employee_id,status) VALUES ('.$cus_id.', NOW(),'.$employee_id[0]["e"]["id"].',1)');

			//Lay ma hoa don moi tao
			$get_invoice = $this->Manager->query("SELECT LAST_INSERT_ID()");
			$id_invoice = '';
			foreach ($get_invoice as $item)
			{
				$id_invoice = $item['0']['LAST_INSERT_ID()'];
			}
			$sum ='';

			//Them chi tiet cua hoa don
			for ($i=0; $i < count($id_array); $i++)
			{
				$quantity = $quantity_array[$i];
				$promotion = $promotion_array[$i];
				$price = $price_array[$i];
				$id = $id_array[$i];
				$sum = $sum + $quantity * $price;
				if ($quantity != 0){
					$this->Manager->query("INSERT INTO wholesale_invoices_wh_wholesales(wholesale_invoice_id,quantity, promotion,price,product_id)
														VALUES (".$id_invoice.",".$quantity.",0,".$price.",".$id.")");
				}
				$promotion = 0;
				$query = $this->Manager->query("SELECT * FROM promotions WHERE quota > 0 AND sell_product=".$id);
				if (sizeof($query) > 0) {
					foreach ($query as $item){
						$promotion = floor($quantity / $item["promotions"]["sell_quantity"]) * $item["promotions"]["promotion_quantity"];
						if ($promotion > $item["promotions"]["quota"]){
							$promotion = $item["promotions"]["quota"];
						}
					}
				}
				if ($promotion != 0)
				{
					$resultPromotion = $this->Manager->query("SELECT promotion_product FROM promotions WHERE sell_product =".$id);
					foreach ($resultPromotion as $item){
						$promotionId = $item["promotions"]["promotion_product"];
					}
					$this->Manager->query("INSERT INTO wholesale_invoices_wh_wholesales(wholesale_invoice_id,quantity, promotion,price,product_id)
														VALUES (".$id_invoice.",".$promotion.",1,".$price.",".$promotionId.")");
				}

				$this->Manager->query("UPDATE products SET quantity_wholesale = quantity_wholesale - ".$quantity." WHERE id='".$id."' ");
				$this->Manager->query("UPDATE promotions SET quota = quota - ".$promotion." WHERE sell_product=".$id);
			}
			$this->Manager->query("UPDATE wholesale_invoices SET total = '".$sum."' WHERE id='".$id_invoice."' ");
			if  ($amount == "*") {
				$this->Manager->query("UPDATE wholesale_invoices SET own = 0 WHERE id='".$id_invoice."' ");
			}
			else {
				$this->Manager->query("UPDATE wholesale_invoices SET own = '".($sum - $amount)."' WHERE id='".$id_invoice."' ");
			}
			$this->Manager->query('COMMIT');
			echo $id_invoice;		}
			catch (Exception $e)
			{
				$this->Manager->query('ROLLBACK');
				echo false;
			}
	}


	function new_cus() {
		$this->autoRender=false;
		$name = $_GET["name"];
		$store = $_GET["store"];
		$mobile = $_GET["mobile"];
		$phone = $_GET["phone"];
		$address = $_GET["address"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("INSERT INTO customers(name,store,address,mobile,phone)
									VALUES ('".$name."','".$store."','".$address."','".$mobile."','".$phone."')");
			$id_cus = '';
			$get_cus_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_cus_id as $item)
			{
				$id_cus = $item['0']['LAST_INSERT_ID()'];
			}
			$this->Manager->query("COMMIT");
			echo $id_cus;
		}
		catch ( Exception $e) {
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}


	function create_delivery_invoice() {
		$this->autoRender=false;
		$list_wh = $_GET["list_wh"];
		$list_note = $_GET["list_note"];
		$list_note = substr($list_note, 0, strlen($list_note) -3 );
		$list_wh = substr($list_wh, 0, strlen($list_wh) -1 );
		$car = $_GET["id_car"];
		$driver = $_GET["id_driver"];
		$trans1 = $_GET["id_trans1"];
		$trans2 = $_GET["id_trans2"];
		$wh_array = explode(',', $list_wh);
		$note_array = explode('/,/', $list_note);
		if($this->Manager->query('INSERT INTO delivery_invoices(time,car_id,driver,delivery_staff_1,delivery_staff_2) VALUES (NOW(),'.$car.','.$driver.','.$trans1.','.$trans2.')'))
		{
			//lay id cua hoa don giao moi tao
			$get_invoice = $this->Manager->query("SELECT LAST_INSERT_ID()");
			$id_invoice = '';
			foreach ($get_invoice as $item)
			{
				$id_invoice = $item['0']['LAST_INSERT_ID()'];

			}
			for ($i = 0; $i < count($wh_array); $i++)
			{
				$this->Manager->query("INSERT INTO delivery_invoices_wholesale_invoices(delivery_invoice_id,wholesale_invoice_id,note)
										VALUES (".$id_invoice.",".$wh_array[$i].",'".$note_array[$i]."')");
				$this->Manager->query("UPDATE wholesale_invoices SET status=2 WHERE id=".$wh_array[$i]);
			}

			echo "Tạo hóa đơn thành công";
		}
		else {
			echo "Không thể tạo hóa đơn";
		}

	}


	//------------------------------------------------------------Code for product
	function edit_price_product_retail() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$price_retail = $_GET["price_retail"];
		$barcode = $_GET["barcode"];
		$this->Manager->query('BEGIN');
		try {
			$this->Manager->query('UPDATE products SET price_retail = '.$price_retail.', barcode = '.$barcode.' WHERE id =' .$id);
			$this->Manager->query('COMMIT');
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query('ROLLBACK');
			echo false;
		}
	}
	
	function edit_price_product_wholesale() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$price_wholesale = $_GET["price_wholesale"];
		$barcode = $_GET["barcode"];
		$this->Manager->query('BEGIN');
		try {
			$this->Manager->query('UPDATE products SET price_wholesale = '.$price_wholesale.', barcode = '.$barcode.' WHERE id =' .$id);
			$this->Manager->query('COMMIT');
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query('ROLLBACK');
			echo false;
		}
	}

	function add_product_retail() {
		$this->autoRender=false;
		$name = $_GET["name"];
		$price_retail = $_GET["price_retail"];
		$unit = $_GET["unit"];
		$type = $_GET["type"];
		$barcode = $_GET["barcode"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("INSERT INTO products(name,product_type_id,unit_id,barcode,price_retail)
									VALUES ('$name','$type','$unit','$barcode','$price_retail')");
			$id_product = '';
			$get_product_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_product_id as $item)
			{
				$id_product = $item['0']['LAST_INSERT_ID()'];
			}
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e){
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}
	
	function add_product_wholesale() {
		$this->autoRender=false;
		$name = $_GET["name"];
		$price_wholesale = $_GET["price_wholesale"];
		$unit = $_GET["unit"];
		$product_retail= $_GET["product_retail"];
		$barcode = $_GET["barcode"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("INSERT INTO products(name,unit_id,barcode,price_wholesale,product_retail)
					VALUES ('$name','$unit','$barcode','$price_wholesale','$product_retail')");
			$id_product = '';
			$get_product_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_product_id as $item)
			{
				$id_product = $item['0']['LAST_INSERT_ID()'];
			}
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e){
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function delete_product() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {

			$this->Manager->query("UPDATE products SET `delete` = 1 WHERE id=".$id);
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}


	//------------------------------------------------------------Code for product type

	function edit_product_type() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$name = $_GET["name"];
		if($this->Manager->query('UPDATE product_types SET name = "'.$name.'" WHERE id =' .$id))
		{
			echo 'Cập nhật thành công';
		}
		else
		{
			echo 'Cập nhật không thành công';
		}
	}

	function add_product_type(){
		$this->autoRender=false;
		$name = $_GET["name"];
		if ($this->Manager->query("INSERT INTO product_types(name)
									VALUES ('".$name."')"))
		{

			$id_product = '';
			$get_product_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_product_id as $item)
			{
				$id_product = $item['0']['LAST_INSERT_ID()'];
			}
			echo $id_product;
		}
		else
		{
			echo "Không thể thêm sản phẩms";
		}
	}


	//------------------------------------------------------------Code for product unit
	function edit_unit(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$father = $_GET["father"];
		$child = $_GET["child"];
		$convert = $_GET["convert"];
		if($this->Manager->query('UPDATE units SET father = "'.$father.'",child = "'.$child.'",`convert` = "'.$convert.'" WHERE id =' .$id))
		{
			echo 'Cập nhật thành công';
		}
		else
		{
			echo 'Cập nhật không thành công';
		}
	}

	function add_unit(){
		$this->autoRender=false;
		$father = $_GET["father"];
		$child = $_GET["child"];
		$convert = $_GET["convert"];
		
		$this->Manager->query('BEGIN');
		try {
			$this->Manager->query("INSERT INTO units(`father`,`child`,`convert`)
									VALUES ('','".$child."','')");
			if($father != null){
				$this->Manager->query("INSERT INTO units(`father`,`child`,`convert`)
									VALUES ('".$father."','','".$convert."')");}
			$this->Manager->query('COMMIT');
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query('ROLLBACK');
			echo false;
		}
	}


	//------------------------------------------------------------Code for promotion
	function edit_promotion() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$sell_quantity = $_GET["sell_quantity"];
		$pro_quantity = $_GET["pro_quantity"];
		$quota = $_GET["quota"];
		$this->Manager->query('BEGIN');
		try {
			$this->Manager->query("UPDATE products p, promotions pro SET p.quantity_retail = p.quantity_retail + pro.quota WHERE pro.promotion_product = p.id AND pro.id=".$id);
			$this->Manager->query('UPDATE promotions SET sell_quantity = '.$sell_quantity.', promotion_quantity = '.$pro_quantity.', quota = '.$quota.' WHERE id =' .$id);
			$this->Manager->query("UPDATE products p, promotions pro SET p.quantity_retail = p.quantity_retail - pro.quota WHERE pro.promotion_product = p.id AND pro.id=".$id);
			$this->Manager->query('COMMIT');
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query('ROLLBACK');
			echo false;
		}
	}

	function add_promotion() {
		$this->autoRender=false;
		$product_sell= $_GET["product_sell"];
		$product_pro = $_GET["product_pro"];
		$quantity_sell = $_GET["quantity_sell"];
		$quantity_pro = $_GET["quantity_pro"];
		$quota = $_GET["quota"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("INSERT INTO promotions(sell_product,sell_quantity,promotion_product,promotion_quantity,quota)
					VALUES ('$product_sell','$quantity_sell','$product_pro','$quantity_pro','$quota')");
			$id_promotion = '';
			$get_promotion_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_promotion_id as $item)
			{
				$id_promotion = $item['0']['LAST_INSERT_ID()'];
			}
			$this->Manager->query("UPDATE products p, promotions pro SET p.quantity_retail = p.quantity_retail - pro.quota WHERE pro.promotion_product = p.id AND pro.id=".$id_promotion);
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e){
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function delete_promotion() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("UPDATE products p, promotions pro SET p.quantity_retail = p.quantity_retail + pro.quota WHERE pro.promotion_product = p.id AND pro.id=".$id);
			$this->Manager->query("DELETE FROM promotions WHERE id=".$id);
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}
	function get_quantity_retail(){
		$this->autoRender=false;
		$product_id= $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
			$quantity_retail = '';
			$get_quantity = $this->Manager->query("SELECT * FROM products p where id=".$product_id);
			foreach ($get_quantity as $item)
			{
				$quantity_retail = $item['p']['quantity_retail'];
			}
			echo $quantity_retail;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}
	//------------------------------------------------------------Code for product vendor
	function edit_vendor(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$name = $_GET["name"];
		$store = $_GET["store"];
		$phone = $_GET["phone"];
		$mobile = $_GET["mobile"];
		$address = $_GET["address"];
		if($this->Manager->query('UPDATE vendors SET name = "'.$name.'",store = "'.$store.'",phone = "'.$phone.'",mobile = "'.$mobile.'",address = "'.$address.'" WHERE id =' .$id))
		{
			echo 'Cập nhật thành công';
		}
		else
		{
			echo 'Cập nhật không thành công';
		}
	}

	function add_vendor(){
		$this->autoRender=false;
		$name = $_GET["name"];
		$store = $_GET["store"];
		$phone = $_GET["phone"];
		$mobile = $_GET["mobile"];
		$address = $_GET["address"];
		if ($this->Manager->query("INSERT INTO vendors(`name`,store,phone,mobile,address)
									VALUES ('".$name."','".$store."','".$phone."','".$mobile."','".$address."')"))
		{

			$id_product = '';
			$get_product_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_product_id as $item)
			{
				$id_product = $item['0']['LAST_INSERT_ID()'];
			}
			echo $id_product;
		}
		else
		{
			echo "Không thể thêm đối tác";
		}
	}


	//------------------------------------------------------------Code for product customer

	function edit_customer(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$amount = $_GET["amount"];
		$name = $_GET["name"];
		$store = $_GET["store"];
		$phone = $_GET["phone"];
		$mobile = $_GET["mobile"];
		$address = $_GET["address"];
		if($this->Manager->query('UPDATE customers SET name = "'.$name.'",store = "'.$store.'",phone = "'.$phone.'",mobile = "'.$mobile.'",address = "'.$address.'",amount='.$amount.' WHERE id =' .$id))
		{
			echo 'Cập nhật thành công';
		}
		else
		{
			echo 'Cập nhật không thành công';
		}
	}


	function add_customer(){
		$this->autoRender=false;
		$name = $_GET["name"];
		$store = $_GET["store"];
		$phone = $_GET["phone"];
		$mobile = $_GET["mobile"];
		$address = $_GET["address"];
		if ($this->Manager->query("INSERT INTO customers(`name`,store,phone,mobile,address)
									VALUES ('".$name."','".$store."','".$phone."','".$mobile."','".$address."')"))
		{

			$id_product = '';
			$get_product_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			foreach ($get_product_id as $item)
			{
				$id_product = $item['0']['LAST_INSERT_ID()'];
			}
			echo $id_product;
		}
		else
		{
			echo "Không thể thêm đối tác";
		}
	}


	//------------------------------------------------------------Code for product user
	function add_user(){
		$this->autoRender=false;
		$name = $_GET["name"];
		$password = $_GET["pass"];
		$pass = Security::hash($password, 'md5', true);
		$email = $_GET["email"];
		$level = $_GET["level"];
		$gender = $_GET["gender"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("INSERT INTO users(username,password,email,user_type,gender)
									VALUES ('".$name."','".$pass."','".$email."','".$level."','".$gender."')");
			$id_product = '';
			$get_product_id = $this->Manager->query("SELECT LAST_INSERT_ID()");
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLlBACK");
			echo false;
		}
	}

	function edit_car(){
		$this->autoRender=false;
		$number = $_GET["number"];
		$id = $_GET["id"];
		if ($this->Manager->query("UPDATE cars SET number='".$number."' WHERE id=".$id." ")){
			echo true;
		}
		else {
			echo false;
		}
	}

	function delete_car() {
		$this->autoRender=false;
		$id = $_GET["id"];
		if ($this->Manager->query("UPDATE cars SET `delete`=1 WHERE id=".$id))
		{
			echo true;
		}
		else
		{
			echo false;
		}
	}


	function new_car(){
		$this->autoRender=false;
		$number = $_GET["number"];
		if ($this->Manager->query("INSERT INTO cars(number) VALUES ('".$number."')"))
		{
			echo true;
		}
		else
		{
			echo false;
		}
	}

	function edit_wholesale_invoice(){
		$this->autoRender=false;
		$new_price = $_GET["new_price"];
		$new_quantity = $_GET["new_quantity"];
		$old_price = 0;
		$old_quantity = 0;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
			$old_row = $this->Manager->query("SELECT * FROM wholesale_invoices_wh_wholesales detail WHERE id=".$id);
			$old_price = $old_row[0]["detail"]["price"];
			$old_quantity = $old_row[0]["detail"]["quantity"];

			$this->Manager->query("UPDATE products SET quantity_wholesale= quantity_wholesale-".$old_quantity."+".$new_quantity." WHERE id=".$old_row[0]["detail"]["product_id"]);

			$this->Manager->query("UPDATE wholesale_invoices_wh_wholesales SET price =".$new_price.",quantity =".$new_quantity."  WHERE id=".$id);
			$this->Manager->query("UPDATE wholesale_invoices SET total = total-".($old_price*$old_quantity)."+".($new_price*$new_quantity)." WHERE
										id=(SELECT wholesale_invoice_id FROM wholesale_invoices_wh_wholesales WHERE id=".$id.")");

			$promotionLine = $this->Manager->query("SELECT * FROM promotions WHERE quota > 0 AND sell_product =".$old_row[0]["detail"]["product_id"]);

			$promotionQuantity = 0;
			if (sizeof($promotionLine) > 0) {
				$promotionQuantity = floor($new_quantity / $promotionLine[0]["promotions"]["sell_quantity"]) * $promotionLine[0]["promotions"]["promotion_quantity"];
				if ($promotionQuantity > $promotionLine[0]["promotions"]["quota"]){
					$promotionQuantity = $promotionLine[0]["promotions"]["quota"];
				}
			}
			$old_quantity_promotion = $this->Manager->query("SELECT quantity FROM wholesale_invoices_wh_wholesales WHERE wholesale_invoice_id=".$old_row[0]["detail"]["wholesale_invoice_id"]."
											AND promotion = 1 AND product_id=".$promotionLine[0]["promotions"]["promotion_product"]);
			$this->Manager->query("UPDATE promotions SET quota = quota + ".$old_quantity_promotion[0]["wholesale_invoices_wh_wholesales"]["quantity"]." WHERE sell_product=".$promotionLine[0]["promotions"]["sell_product"]);
			$this->Manager->query("DELETE FROM wholesale_invoices_wh_wholesales WHERE wholesale_invoice_id=".$old_row[0]["detail"]["wholesale_invoice_id"]."
											AND promotion = 1 AND product_id=".$promotionLine[0]["promotions"]["promotion_product"]);


			if ($promotionQuantity != 0) {
				$this->Manager->query("INSERT INTO wholesale_invoices_wh_wholesales(wholesale_invoice_id,quantity, promotion,price,product_id)
														VALUES (".$old_row[0]["detail"]["wholesale_invoice_id"].",".$promotionQuantity.",1,".$new_price.",".$promotionLine[0]["promotions"]["promotion_product"].")");
				$this->Manager->query("UPDATE promotions SET quota = quota - ".$promotionQuantity." WHERE sell_product=".$promotionLine[0]["promotions"]["sell_product"]);
			}
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e) {
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}


	function delete_detail_wholesale_inv(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		if ($this->Manager->query("DELETE FROM wholesale_invoices_wh_wholesales WHERE id=".$id))
		{
			$this->Manager->query("COMMIT");
			echo true;
		}
		else
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function delete_wholesale_inv() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
			$result = $this->Manager->query("SELECT * FROM wholesale_invoices_wh_wholesales detail WHERE detail.wholesale_invoice_id =".$id);
			foreach ($result as $item){
				if ($item["detail"]["promotion"] == 1){
					$this->Manager->query("UPDATE products SET quantity_retail = quantity_retail +".$item["detail"]["quantity"]." WHERE id =".$item["detail"]["product_id"]);
				} else {
					$this->Manager->query("UPDATE products SET quantity_wholesale = quantity_wholesale +".$item["detail"]["quantity"]." WHERE id =".$item["detail"]["product_id"]);
				}
			}
			$this->Manager->query("DELETE FROM wholesale_invoices WHERE id=".$id);
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch(Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function edit_warehouse_invoice(){
		$this->autoRender=false;
		$price = $_GET["cost"];
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		$result = $this->Manager->query("SELECT * FROM wh_invoices_wh_wholesales detail WHERE id=".$id);
		if ($this->Manager->query("UPDATE wh_invoices_wh_wholesales SET cost=".$price." WHERE id=".$id))
		{
			$this->Manager->query("UPDATE wh_invoices SET total=total-".$result[0]["detail"]["quantity"]*$result[0]["detail"]["cost"]."+
									".$result[0]["detail"]["quantity"]*$price." WHERE id=".$result[0]["detail"]["wh_invoice_id"]);
			$this->Manager->query("COMMIT");
			echo true;
		}
		else
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function delete_detail_warehouse_inv(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		if ($this->Manager->query("DELETE FROM wh_invoices_wh_wholesales WHERE id=".$id))
		{
			$this->Manager->query("COMMIT");
			echo true;
		}
		else
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function delete_transfer_inv(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		if ($this->Manager->query("DELETE FROM transfer_invoices WHERE id=".$id))
		{

			$this->Manager->query("COMMIT");
			echo true;
		}
		else
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function delete_product_type(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		if ($this->Manager->query("UPDATE product_types set `delete` = 1 WHERE id=".$id))
		{
			$this->Manager->query("COMMIT");
			echo true;
		}
		else
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}

	}


	function delete_unit(){
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		if ($this->Manager->query("UPDATE units set `delete` = 1 WHERE id=".$id))
		{
			$this->Manager->query("COMMIT");
			echo true;
		}
		else
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}

	function add_employee(){
		$this->autoRender=false;
		$name = $_GET["name"];
		$phone = $_GET["phone"];
		$type = $_GET["type"];
		$user = $_GET["user"];
		$start = $_GET["start"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("INSERT INTO employees(name,phone,user_id,employee_type_id,start)
									VALUES ('".$name."','".$phone."',".$user.",".$type.",'".$start."')");
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLlBACK");
			echo false;
		}
	}

	function check_de_invoice() {
		$this->autoRender=false;
		$list_check = $_GET["list_check"];
		$list_id = $_GET["list_id"];
		$list_id = substr($list_id, 0, strlen($list_id) -1 );
		$list_check = substr($list_check, 0, strlen($list_check) -1 );
		$id_array = explode(',', $list_id);
		$check_array = explode(',', $list_check);
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
			for ($i = 0; $i < count($id_array); $i++){
				if ($check_array[$i] == 1) {
					$this->Manager->query("UPDATE wholesale_invoices SET wholesale_invoices.status = 3 where id = $id_array[$i]");
				}
				if ($check_array[$i] == 0) {
					$invoice_detail = $this->Manager->query("SELECT * FROM wholesale_invoices_wh_wholesales detail WHERE wholesale_invoice =".$id_array[$i]);
					foreach ($invoice_detail as $item){
						if ($item["detail"]["promotion"] != 0){
							$this->Manager->query("UPDATE products SET quantity_wholesale = quantity_wholesale +".$item["detail"]["quantity"]."WHERE id=".$item["detail"]["product_id"]);
						}
						else {
							$this->Manager->query("UPDATE promotions SET quota = quota +".$item["detail"]["quantity"]."WHERE sell_product=".$item["detail"]["product_id"]);
						}
					}
					$this->Manager->query("UPDATE wholesale_invoices SET wholesale_invoices.delete = 1 where id = $id_array[$i]");
				}
			}
			$this->Manager->query("UPDATE delivery_invoices SET delivery_invoices.check	 = 1 where id = $id");
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLlBACK");
			echo false;
		}
	}

	function update_de_invoice() {
		$this->autoRender=false;
		$list_check = $_GET["list_check"];
		$list_id = $_GET["list_id"];
		$list_id = substr($list_id, 0, strlen($list_id) -1 );
		$list_check = substr($list_check, 0, strlen($list_check) -1 );
		$id_array = explode(',', $list_id);
		$check_array = explode(',', $list_check);
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
			$this->Manager->query("DELETE FROM delivery_invoices_wholesale_invoices where delivery_invoice_id = $id");
			for ($i = 0; $i < count($id_array); $i++){
				$this->Manager->query("INSERT INTO delivery_invoices_wholesale_invoices(wholesale_invoice_id,delivery_invoice_id) VALUES($id_array[$i],$id)");
				if ($check_array[$i] == 1) {
					$this->Manager->query("UPDATE wholesale_invoices SET wholesale_invoices.status = 3 where id = $id_array[$i]");
				}
				if ($check_array[$i] == 0) {
					$this->Manager->query("UPDATE wholesale_invoices SET wholesale_invoices.status = 1 where id = $id_array[$i]");
				}
			}
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLlBACK");
			echo false;
		}
	}

	function barcode_decode() {
		$this->autoRender=false;
		$barcode = $_GET["barcode"];
		$query = "SELECT id FROM products WHERE barcode='".$barcode."'";
		$result = $this->Manager->query($query);
		$id = '';
		foreach ($result as $item)
		{
			$id = $item["products"]["id"];
		}
		echo $id;
	}

	function barcode_decode_wholesale() {
		$this->autoRender=false;
		$barcode = $_GET["barcode"];
		$query = "SELECT id,quantity_wholesale FROM products WHERE barcode='".$barcode."'";
		$result = $this->Manager->query($query);
		$id = '';
		foreach ($result as $item)
		{
			if ($item["products"]["quantity_wholesale"] != 0){
				$id = $item["products"]["id"];
			}
			else {
				$id = '-1';
			}
		}
		echo $id;
	}
	
	function delete_employee() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
	
			$this->Manager->query("UPDATE employees SET `delete` = 1 WHERE id=".$id);
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}
	
	function delete_user() {
		$this->autoRender=false;
		$id = $_GET["id"];
		$this->Manager->query("BEGIN");
		try {
	
			$this->Manager->query("UPDATE users SET `delete` = 1 WHERE id=".$id);
			$this->Manager->query("COMMIT");
			echo true;
		}
		catch (Exception $e)
		{
			$this->Manager->query("ROLLBACK");
			echo false;
		}
	}


}


?>